import 'dart:collection';
import 'dart:convert';
import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:news/com.comm/contants/constant.dart';
import 'package:news/com.comm/model/db_utils.dart';
import 'package:spreadsheet_decoder/spreadsheet_decoder.dart';

import '../utils/StringUtils.dart';
import '../utils/utils.dart';
import '../utils/widget_utils.dart';

/**
 * 多语言解析
 */
class ParseTranslateExcel extends StatefulWidget {
  final String resPath;

  ParseTranslateExcel({Key? key, required this.resPath}) : super(key: key);

  @override
  _ParseTranslateExcelState createState() => _ParseTranslateExcelState();
}

class _ParseTranslateExcelState extends State<ParseTranslateExcel> {
  final TextEditingController _controller_file =
      TextEditingController(); //要解析的多语言文档路径
  final TextEditingController _controller_out = TextEditingController(); //解析结果
  final TextEditingController _controller_error_path =
      TextEditingController(); //导入的故障列表路径
  final TextEditingController _controller_json_translate_tag =
      TextEditingController(); //要解析的故障码多语言代号
  String? _selectedSheetName = ""; // 选中的要解析的表名
  String? _selectedLanguageName = ""; // 选中的要解析的多语言名称
  List<String> list_sheet = []; // 解析的文档列表
  List<String> list_language_keys = []; // 多语言类型列表

  @override
  void initState() {
    super.initState();
  }

  /**
   * 选择故障文件
   */
  Future<void> _pickJsonErrorFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();
    if (result != null) {
      setState(() {
        _controller_error_path.text = result.files.single.path!;
      });
    } else {
      // 用户取消了选择
      setState(() {
        _controller_error_path.text = "";
      });
    }
  }

  /**
   * 选择文件
   */
  Future<void> _pickFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();
    if (result != null) {
      setState(() {
        _controller_file.text = result.files.single.path!;
        _readExcelSheets();
        _readExcelLanguageList();
      });
    } else {
      // 用户取消了选择
      setState(() {
        _controller_file.text = "";
      });
    }
  }

  /**
   * 读取多语言文档 的表名列表
   */
  Future<void> _readExcelSheets() async {
    String excelPath = _controller_file.text.trim();
    if (excelPath.isEmpty) {
      return;
    }
    // 检查文件是否存在
    final file = File(excelPath);
    if (await file.exists()) {
      print("excelPath:" + excelPath);
      final bytes = await file.readAsBytesSync();
      var decoder = SpreadsheetDecoder.decodeBytes(bytes);
      list_sheet.clear();
      for (var table in decoder.tables.keys) {
        list_sheet.add(table);
      }
      setState(() {
        if (list_sheet.isNotEmpty) {
          _selectedSheetName = list_sheet.first.toString().trim();
        }
      });
    } else {
      print('文件不存在: $excelPath');
    }
  }

  /**
   * 读取多语言文档 所有语言类型
   */
  Future<void> _readExcelLanguageList() async {
    String excelPath = _controller_file.text.trim();
    if (excelPath.isEmpty) {
      return;
    }
    // 检查文件是否存在
    final file = File(excelPath);
    if (await file.exists()) {
      print("excelPath:" + excelPath);
      final bytes = await file.readAsBytesSync();
      var decoder = SpreadsheetDecoder.decodeBytes(bytes);
      if (_selectedSheetName!.isEmpty) {
        showToast("请先选择解析的多语言！");
        return;
      }
      var table = decoder.tables[_selectedSheetName];
      if (table == null) {
        print("table is null:");
        return;
      }
      list_language_keys.clear();
      var rows = table.rows;
      if (rows.isEmpty) {
        print("rows is null:");
        return;
      }
      // 打印每一行的内容
      rows.first.forEach((cell) {
        list_language_keys.add(cell.toString().trim());
      });
      setState(() {
        if (list_language_keys.isNotEmpty) {
          _selectedLanguageName = list_language_keys.first.toString().trim();
        }
      });
    } else {
      print('文件不存在: $excelPath');
    }
  }

  /**
   * 解析当前选中的多语言内容
   */
  Future<void> _parseSelectLanguage() async {
    String excelPath = _controller_file.text.trim();
    if (excelPath.isEmpty) {
      return;
    }
    // 检查文件是否存在
    final file = File(excelPath);
    if (await file.exists()) {
      print("excelPath:" + excelPath);
      final bytes = await file.readAsBytesSync();
      var decoder = SpreadsheetDecoder.decodeBytes(bytes);
      if (_selectedSheetName!.isEmpty) {
        showToast("请先选择解析的文档表名！");
        return;
      }
      if (_selectedLanguageName!.isEmpty) {
        showToast("请先选择解析的多语言种类！");
        return;
      }
      var table = decoder.tables[_selectedSheetName];
      if (table == null) {
        print("table is null:");
        return;
      }
      var rows = table.rows;
      if (rows.isEmpty) {
        print("rows is null:");
        return;
      }
      int indexSelectLanguage = 1; //当前选中的语言角标
      for (int i = 0; i < list_language_keys.length; i++) {
        if (_selectedLanguageName == list_language_keys[i]) {
          indexSelectLanguage = i;
          break;
        }
      }
      String data = "";
      data = data + "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
      data = data + "<resources>\n";
      // 打印每一行的内容
      for (int i = 1; i < rows.length; i++) {
        var cellList = rows[i];
        var stringCode = cellList[0];
        var stringValue = cellList[indexSelectLanguage].toString().trim();
        data = data +
            "    <string name=\"${stringCode}\">${stringValue}</string>\n";
        print("index:${i}|key:${stringCode}|value:${stringValue}");
      }
      data = data + "</resources>";
      setState(() {
        _controller_out.text = data;
      });
    } else {
      print('文件不存在: $excelPath');
    }
  }

  /**
   * 解析当前选中的故障码多语言内容
   */
  Future<void> _parseSelectErrorJsonLanguage() async {
    String excelPath = _controller_file.text.trim();
    String jsonErrorPath = _controller_error_path.text.trim();
    // 故障码 当前输入的多语言代号
    String jsonTranslateTag = _controller_json_translate_tag.text.trim();
    if (excelPath.isEmpty ||
        jsonErrorPath.isEmpty ||
        jsonTranslateTag.isEmpty) {
      return;
    }
    // 检查文件是否存在
    final fileJsonError = File(jsonErrorPath);
    final fileExcel = File(excelPath);
    bool isExcelExist = await fileExcel.existsSync();
    bool isJsonErrorExist = await fileJsonError.existsSync();
    print("isExcelExist:${isExcelExist}|isJsonErrorExist:${isJsonErrorExist}");
    print("excelPath:${excelPath}|jsonErrorPath:${jsonErrorPath}");
    print(
        "_selectedSheetName:${_selectedSheetName}|_selectedLanguageName:${_selectedLanguageName}");
    if (isExcelExist && isJsonErrorExist) {
      final bytes = await fileExcel.readAsBytesSync();
      var decoder = SpreadsheetDecoder.decodeBytes(bytes);
      if (_selectedSheetName!.isEmpty) {
        showToast("请先选择解析的文档表名！");
        return;
      }
      if (_selectedLanguageName!.isEmpty) {
        showToast("请先选择解析的多语言种类！");
        return;
      }
      var table = decoder.tables[_selectedSheetName];
      if (table == null) {
        print("table is null:");
        return;
      }
      var rows = table.rows;
      if (rows.isEmpty) {
        print("rows is null:");
        return;
      }
      int indexSelectLanguage = 1; //当前选中的语言角标
      for (int i = 0; i < list_language_keys.length; i++) {
        if (_selectedLanguageName == list_language_keys[i]) {
          indexSelectLanguage = i;
          break;
        }
      }
      var listConfig =   await DbUtils().loadTranslateConfig();
      var list_error = HashMap<String,String>();
      listConfig.forEach((element) {
        list_error[element[Constant.shortName]] = element[Constant.errorName];
      });
      var data = [];
      // 打印每一行的内容
      for (int i = 1; i < rows.length; i++) {
        var cellList = rows[i];
        var item = {};
        for (int j = 0; j < cellList.length; j++) {
          var stringKey = "";
          if (j == 0) {
            stringKey = "code";
          } else if (j == indexSelectLanguage) {
            stringKey = jsonTranslateTag;
          } else {
            if (list_error.containsKey(list_language_keys[j])) {
              stringKey = list_error[list_language_keys[j]]!;
            } else {
              stringKey = list_language_keys[j].trim();
            }
          }
          var stringValue = cellList[j];
          item[stringKey] = stringValue;
        }
        print("index:${i}|item:${item}");
        data.add(item);
      }
      //原旧的故障码多语言
      final jsonOldContent = await fileJsonError.readAsStringSync();
      List<dynamic> jsonListOld = jsonDecode(jsonOldContent);
      if (jsonListOld.isEmpty) {
        return;
      }
      for (int i = 0; i < jsonListOld.length; i++) {
        var item = jsonListOld[i];
        if(data.length>i) {
          item[jsonTranslateTag] = data[i][jsonTranslateTag];
        }else{
          item[jsonTranslateTag] = "翻译缺失";
        }
      }
      // 使用 jsonEncode 函数进行格式化输出
      String prettyPrint = JsonEncoder.withIndent('  ').convert(jsonListOld);
      setState(() {
        _controller_out.text = prettyPrint;
      });
    } else {
      showToast("当前文件解析失败！");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        SizedBox(
          height: 16,
        ),
        SizedBox(
            width: 1000,
            child: Row(children: [
              SizedBox(
                  width: 200,
                  child: getTextWidget(16, "要解析的多语言文件 :", Colors.black)),
              SizedBox(
                width: 16,
              ),
              SizedBox(
                  width: 640,
                  child: TextField(
                    controller: _controller_file,
                    decoration: InputDecoration(
                      labelText: '请输入要解析的多语言文档',
                      hintText: '请输入要解析的多语言文档',
                      border: OutlineInputBorder(),
                    ),
                  )),
              Padding(
                  padding: EdgeInsets.only(left: 8),
                  child: SizedBox(
                      height: 40,
                      child: ElevatedButton(
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue,
                          ),
                          onPressed: () {
                            _pickFile();
                          },
                          child: getTextWidget(16, "文档选择", Colors.white)))),
            ])),
        SizedBox(
          height: 16,
        ),
        Row(children: [
          SizedBox(
              width: 200, child: getTextWidget(16, "请选择文档表名 :", Colors.black)),
          SizedBox(
            width: 16,
          ),
          DropdownButton<String>(
              value: _selectedSheetName,
              hint: Text('请选择一个选项'),
              icon: Icon(Icons.arrow_downward),
              iconSize: 24,
              elevation: 16,
              style: TextStyle(color: Colors.deepPurple),
              underline: Container(
                height: 2,
                color: Colors.deepPurpleAccent,
              ),
              onChanged: (String? newValue) {
                setState(() {
                  _selectedSheetName = newValue;
                  _readExcelLanguageList();
                });
              },
              items: list_sheet.map<DropdownMenuItem<String>>((String item) {
                return DropdownMenuItem<String>(
                  value: item,
                  child: Text(item),
                );
              }).toList())
        ]),
        SizedBox(
          height: 16,
        ),
        Row(children: [
          SizedBox(
              width: 200,
              child: getTextWidget(16, "请选择解析的多语言 :", Colors.black)),
          SizedBox(
            width: 16,
          ),
          DropdownButton<String>(
              value: _selectedLanguageName,
              hint: Text('请选择一个选项'),
              icon: Icon(Icons.arrow_downward),
              iconSize: 24,
              elevation: 16,
              style: TextStyle(color: Colors.deepPurple),
              underline: Container(
                height: 2,
                color: Colors.deepPurpleAccent,
              ),
              onChanged: (String? newValue) {
                setState(() {
                  _selectedLanguageName = newValue;
                });
              },
              items: list_language_keys
                  .map<DropdownMenuItem<String>>((String item) {
                return DropdownMenuItem<String>(
                  value: item,
                  child: Text(item),
                );
              }).toList()),
          SizedBox(
            width: 16,
          ),
          SizedBox(
              width: 260,
              child: TextField(
                controller: _controller_json_translate_tag,
                decoration: InputDecoration(
                  labelText: '请输入当前选中的多语言代号',
                  hintText: '请输入当前选中的多语言代号',
                  border: OutlineInputBorder(),
                ),
              ))
        ]),
        SizedBox(
          height: 16,
        ),
        Row(children: [
          SizedBox(
              width: 200, child: getTextWidget(16, "故障码路径：", Colors.black)),
          SizedBox(width: 18),
          Expanded(
              child: TextField(
            controller: _controller_error_path,
            decoration: InputDecoration(
              labelText: '请输入故障码文件路径',
              hintText: '请输入故障码文件路径',
              border: OutlineInputBorder(),
            ),
          )),
          SizedBox(
            width: 16,
          ),
          SizedBox(
              height: 40,
              child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.blue,
                  ),
                  onPressed: () {
                    _pickJsonErrorFile();
                  },
                  child: getTextWidget(16, "文件选择", Colors.white))),
        ]),
        SizedBox(
          height: 16,
        ),
        Container(
            width: 1000,
            constraints: BoxConstraints(
              maxHeight: 224.0, // 设置最大高度
            ),
            child: TextField(
              maxLines: null,
              minLines: 18,
              controller: _controller_out,
              style: TextStyle(
                fontSize: 18.0,
              ),
              // 使用TextEditingController来管理TextField的值
              decoration: InputDecoration(
                hintText: '解析多语言内容空空如也~~~',
                border: OutlineInputBorder(),
              ),
            )),
        SizedBox(
          height: 16,
        ),
        Row(children: <Widget>[
          Expanded(
              child: SizedBox(
            height: 1,
          )),
          TextButton(
            child: Text("解析多语言"),
            onPressed: () {
              String keyTag = _controller_file.text.trim();
              if (keyTag.isEmpty) {
                showToast("多语言文档路径不能为空");
                return;
              }
              _parseSelectLanguage();
            },
          ),
          SizedBox(
            width: 16,
          ),
          TextButton(
            child: Text("解析故障码"),
            onPressed: () {
              // 多语言 excel 文件路径
              String translateFilePath = _controller_file.text.trim();
              // 故障码 当前输入的多语言代号
              String jsonTranslateTag =
                  _controller_json_translate_tag.text.trim();
              // 故障码json 文件
              String jsonTranslateFilePath = _controller_error_path.text.trim();
              if (translateFilePath.isEmpty) {
                showToast("多语言文档路径不能为空！");
                return;
              }
              if (jsonTranslateTag.isEmpty) {
                showToast("当前多语言代号不能为空！");
                return;
              }
              if (jsonTranslateFilePath.isEmpty) {
                showToast("当前故障码路径不能为空！");
                return;
              }
              _parseSelectErrorJsonLanguage();
            },
          ),
          SizedBox(
            width: 16,
          ),
          TextButton(
            child: Text("取消"),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
        ]),
      ],
    );
  }
}
